package com.hk.blog.service.impl;

import com.hk.blog.domain.PermissionMenu;
import com.hk.blog.repository.jpa.PermissionMenuRepository;
import com.hk.blog.service.PermissionMenuService;
import com.hk.commons.util.CollectionUtils;
import com.hk.core.data.jpa.repository.BaseJpaRepository;
import com.hk.core.service.jpa.impl.JpaServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;

/**
 * @author Kevin
 * @date 2022-07-02 19:48
 */
@Service
@RequiredArgsConstructor
public class PermissionMenuServiceImpl extends JpaServiceImpl<PermissionMenu, Long>
        implements PermissionMenuService {

    private final PermissionMenuRepository permissionMenuRepository;

    @Override
    protected BaseJpaRepository<PermissionMenu, Long> getBaseRepository() {
        return permissionMenuRepository;
    }

    @Override
    @Transactional
    public void updatePermMenus(Long permissionId, Set<Long> menuIds) {
        permissionMenuRepository.deleteByPermissionId(permissionId);
        if (CollectionUtils.isNotEmpty(menuIds)) {
            var list = new ArrayList<PermissionMenu>(menuIds.size());
            for (var item : menuIds) {
                list.add(new PermissionMenu().setPermissionId(permissionId).setMenuId(item));
            }
            permissionMenuRepository.saveAll(list);
        }
    }

    @Override
    public Set<Long> findMenuIdsByPermissionId(Long permissionId) {
        return Objects.isNull(permissionId) ? Collections.emptySet() :
                permissionMenuRepository.findMenuIdsByPermissionId(permissionId);
    }

    @Override
    public Set<Long> findPermissionIdsByMenuId(Long menuId) {
        return Objects.isNull(menuId) ? Collections.emptySet() :
                permissionMenuRepository.findPermissionIdsByMenuId(menuId);
    }

}
